package com.ruoyi.module.service.impl;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.module.domain.DictBook;
import com.ruoyi.module.domain.DictWord;
import com.ruoyi.module.mapper.DictBookMapper;
import com.ruoyi.module.mapper.DictWordMapper;
import com.ruoyi.module.service.IDictWordImportService;

/**
 * 词典单词导入Service业务层处理
 * 
 * @author ruoyi
 */
@Service
public class DictWordImportServiceImpl implements IDictWordImportService 
{
    private static final Logger log = LoggerFactory.getLogger(DictWordImportServiceImpl.class);

    @Autowired
    private DictWordMapper dictWordMapper;

    @Autowired
    private DictBookMapper dictBookMapper;

    /**
     * 从JSON文件导入单词到数据库
     */
    @Override
    @Transactional
    public AjaxResult importWordsFromJson(String bookId, String jsonFilePath, String username) 
    {
        try {
            // 验证词典是否存在
            DictBook book = dictBookMapper.selectDictBookById(bookId);
            if (book == null) {
                return AjaxResult.error("词典不存在: " + bookId);
            }

            // 检查是否已经导入
            int existingCount = dictWordMapper.countWordsByBookId(bookId);
            if (existingCount > 0) {
                return AjaxResult.error("词典已导入 " + existingCount + " 个单词，请先清空后再导入");
            }

            // 读取JSON文件
            String jsonContent = new String(Files.readAllBytes(Paths.get(jsonFilePath)), "UTF-8");
            
            return importWordsFromJsonContent(bookId, jsonContent, username);
        }
        catch (IOException e) {
            log.error("读取JSON文件失败: {}", e.getMessage());
            return AjaxResult.error("读取JSON文件失败: " + e.getMessage());
        }
        catch (Exception e) {
            log.error("导入词典单词失败: {}", e.getMessage(), e);
            return AjaxResult.error("导入失败: " + e.getMessage());
        }
    }

    /**
     * 从JSON内容字符串导入单词到数据库
     */
    @Override
    @Transactional
    public AjaxResult importWordsFromJsonContent(String bookId, String jsonContent, String username) 
    {
        try {
            // 解析JSON
            JSONArray jsonArray = JSON.parseArray(jsonContent);
            if (jsonArray == null || jsonArray.isEmpty()) {
                return AjaxResult.error("JSON内容为空或格式错误");
            }

            List<DictWord> words = new ArrayList<>();
            int sortOrder = 1;

            // 解析每个单词
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject wordJson = jsonArray.getJSONObject(i);
                DictWord word = parseWordFromJson(wordJson, bookId, sortOrder++, username);
                if (word != null) {
                    words.add(word);
                }

                // 每1000条批量插入一次
                if (words.size() >= 1000) {
                    dictWordMapper.batchInsertDictWord(words);
                    words.clear();
                    log.info("已导入 {} 个单词到词典 {}", i + 1, bookId);
                }
            }

            // 插入剩余的单词
            if (!words.isEmpty()) {
                dictWordMapper.batchInsertDictWord(words);
            }

            int totalCount = jsonArray.size();
            
            // 更新词典的is_loaded状态和词汇数量
            DictBook book = dictBookMapper.selectDictBookById(bookId);
            if (book != null) {
                book.setLength(totalCount);
                // 这里需要添加is_loaded字段到DictBook类
                dictBookMapper.updateDictBook(book);
            }

            log.info("成功导入词典 {} 的 {} 个单词", bookId, totalCount);
            return AjaxResult.success("成功导入 " + totalCount + " 个单词");
        }
        catch (Exception e) {
            log.error("导入词典单词失败: {}", e.getMessage(), e);
            return AjaxResult.error("导入失败: " + e.getMessage());
        }
    }

    /**
     * 批量导入目录下所有词典的单词
     */
    @Override
    @Transactional
    public AjaxResult batchImportAllDictWords(String dictPath, String username) 
    {
        try {
            File dictDir = new File(dictPath);
            if (!dictDir.exists() || !dictDir.isDirectory()) {
                return AjaxResult.error("词典目录不存在: " + dictPath);
            }

            // 查询所有未导入的词典
            List<DictBook> allBooks = dictBookMapper.selectDictBookList(new DictBook());
            int successCount = 0;
            int failCount = 0;
            StringBuilder message = new StringBuilder();

            for (DictBook book : allBooks) {
                // 检查是否已导入
                int existingCount = dictWordMapper.countWordsByBookId(book.getId());
                if (existingCount > 0) {
                    message.append(String.format("跳过已导入的词典: %s (%d个单词)\n", book.getName(), existingCount));
                    continue;
                }

                // 获取JSON文件路径
                String url = book.getUrl();
                if (StringUtils.isEmpty(url)) {
                    message.append(String.format("跳过无文件路径的词典: %s\n", book.getName()));
                    failCount++;
                    continue;
                }

                // 提取文件名
                String fileName = url.substring(url.lastIndexOf("/") + 1);
                File jsonFile = new File(dictDir, fileName);

                if (!jsonFile.exists()) {
                    message.append(String.format("找不到文件: %s (词典: %s)\n", fileName, book.getName()));
                    failCount++;
                    continue;
                }

                // 导入单词
                AjaxResult result = importWordsFromJson(book.getId(), jsonFile.getAbsolutePath(), username);
                if (result.get("code").equals(200)) {
                    successCount++;
                    message.append(String.format("✓ 成功导入词典: %s\n", book.getName()));
                } else {
                    failCount++;
                    message.append(String.format("✗ 导入失败: %s - %s\n", book.getName(), result.get("msg")));
                }
            }

            message.insert(0, String.format("批量导入完成: 成功 %d 个, 失败 %d 个\n\n", successCount, failCount));
            return AjaxResult.success(message.toString());
        }
        catch (Exception e) {
            log.error("批量导入词典失败: {}", e.getMessage(), e);
            return AjaxResult.error("批量导入失败: " + e.getMessage());
        }
    }

    /**
     * 清空词典的所有单词
     */
    @Override
    @Transactional
    public int deleteWordsByBookId(String bookId) 
    {
        return dictWordMapper.deleteDictWordByBookId(bookId);
    }

    /**
     * 从JSON对象解析单词
     */
    private DictWord parseWordFromJson(JSONObject json, String bookId, int sortOrder, String username) 
    {
        try {
            DictWord word = new DictWord();
            word.setBookId(bookId);
            word.setSortOrder(sortOrder);
            word.setStatus("0");
            word.setCreateBy(username);
            word.setCreateTime(new Date());

            // 单词名称
            String wordName = json.getString("name");
            if (StringUtils.isEmpty(wordName)) {
                wordName = json.getString("word");
            }
            if (StringUtils.isEmpty(wordName)) {
                log.warn("跳过无单词名称的条目");
                return null;
            }
            word.setWord(wordName);

            // 翻译 - 可能是数组或字符串
            Object transObj = json.get("trans");
            if (transObj != null) {
                if (transObj instanceof JSONArray) {
                    JSONArray transArray = (JSONArray) transObj;
                    word.setTranslation(String.join("; ", transArray.toJavaList(String.class)));
                } else {
                    word.setTranslation(transObj.toString());
                }
            }

            // 音标
            word.setPhoneticUs(json.getString("usphone"));
            word.setPhoneticUk(json.getString("ukphone"));

            // 例句
            String sentence = json.getString("sentence");
            if (StringUtils.isEmpty(sentence)) {
                sentence = json.getString("example");
            }
            word.setExampleSentence(sentence);

            // 英文释义
            String definition = json.getString("definition");
            if (StringUtils.isEmpty(definition)) {
                definition = json.getString("meaning");
            }
            word.setWordDefinition(definition);

            return word;
        }
        catch (Exception e) {
            log.error("解析单词JSON失败: {}", e.getMessage());
            return null;
        }
    }
}

